package com.estore.dao;

import com.estore.entity.OrderItem;
import com.estore.util.DBConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

//������ϸ��Ĳ���
public class OrderItemDao {
    private Connection conn = null;
    private PreparedStatement ps = null;

    public OrderItemDao() {
        conn = DBConnection.getConnection();
    }

    public boolean insertOrderItem(OrderItem form) {
        try {
            ps = conn.prepareStatement("insert into tb_order_item(order_id,product_id,product_name,product_price,amount) values (?,?,?,?,?)");
            ps.setString(1, form.getOrderId());
            ps.setInt(2, form.getProductId());
            ps.setString(3, form.getProductName());
            ps.setFloat(4, form.getProductPrice());
            ps.setInt(5, form.getAmount());
            ps.executeUpdate();
            ps.close();
            return true;
        } catch (SQLException ex) {
            System.out.println("SQL语句有误");
            return false;
        }
    }

    /**
     * 根据订单id查询订单明细
     *
     * @param orderId
     * @return
     */
    public List<OrderItem> findByOrderID(String orderId) {

        List<OrderItem> list = new ArrayList();
        OrderItem orderDetail = null;
        ProductDao goodsDao = new ProductDao();
        try {
            ps = conn.prepareStatement(
                    "select * from tb_order_item where order_id=?");
            ps.setString(1, orderId);            //���ݲ���orderIdֵ
            ResultSet rs = ps.executeQuery();    //ִ�в�ѯ����RS
            while (rs.next()) {            //ѭ��ÿһ�ֶΣ�������Ʒ��ϸ����
                orderDetail = new OrderItem();
                orderDetail.setOrderId(rs.getString(2));
                orderDetail.setProductId(rs.getInt(3));
                orderDetail.setProductName(rs.getString(4));
                orderDetail.setProductPrice(rs.getFloat(5));
                orderDetail.setAmount(rs.getInt(6));
                list.add(orderDetail);//��ĳһ��Ʒ��ϸ���������list
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return list;
    }

    // ɾ���ӱ�Ĳ���
    public void deleteOrderItems(String orderId) {
        try {
            ps = conn
                    .prepareStatement("delete from tb_order_item where order_id=?");
            ps.setString(1, orderId);
            ps.executeUpdate();
            ps.close();
        } catch (SQLException ex) {
        }

    }
}

